﻿using System;
using System.Collections.Generic;
using System.Reflection;

namespace HYCodeBase.ObjectPersistentSuit
{
	public class TypeFinder
	{
		private TypeFinder()
		{
			this.m_lstAllType = this.GetAllTypes();
		}

		public static TypeFinder GetTypeFinder(bool ifReset = false)
		{
			if (TypeFinder.m_singleTag == null || ifReset)
			{
				TypeFinder.m_singleTag = new TypeFinder();
			}
			return TypeFinder.m_singleTag;
		}

		public List<Type> FindTypesInheritFromInput(Type inputBaseType)
		{
			if (this.m_dicKeyTypeForListTypes.ContainsKey(inputBaseType))
			{
				return this.m_dicKeyTypeForListTypes[inputBaseType];
			}
			List<Type> list = new List<Type>();
			foreach (Type type in this.m_lstAllType)
			{
				if (inputBaseType.IsAssignableFrom(type))
				{
					list.Add(type);
				}
			}
			this.m_dicKeyTypeForListTypes.Add(inputBaseType, list);
			return list;
		}

		private List<Type> GetAllTypes()
		{
			List<Type> list = new List<Type>();
			new List<Assembly>();
			foreach (Assembly assembly in AssemblyUtility.GetAllAssembly(false))
			{
				try
				{
					foreach (Type type in assembly.GetTypes())
					{
						if (null != type && typeof(ITransformerTag).IsAssignableFrom(type))
						{
							list.Add(type);
						}
					}
				}
				catch (Exception)
				{
				}
			}
			return list;
		}

		private List<Type> m_lstAllType = new List<Type>();

		private Dictionary<Type, List<Type>> m_dicKeyTypeForListTypes = new Dictionary<Type, List<Type>>();

		private static TypeFinder m_singleTag;
	}
}
